package com.igd.socket.sdk.nio.simple_reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;

public class MultiThreadWorkHandler implements Runnable {
	
	int cores = Runtime.getRuntime().availableProcessors();
	
	ThreadPoolExecutor threadPoolExecutor =  new ThreadPoolExecutor(cores, cores, 10, TimeUnit.MINUTES, new LinkedBlockingQueue<>(cores * 10), new CallerRunsPolicy());
	
	private SocketChannel socketChannel;
	
	public MultiThreadWorkHandler(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
	}
 
	@Override
	public void run() {
		System.out.println("Server work---isConnected：" + socketChannel.isConnected() + " isOpen：" + socketChannel.isOpen() + " isRegistered：" + socketChannel.isRegistered());
		threadPoolExecutor.submit(new Process(socketChannel));
	}
	
	class Process implements Runnable {
		
		private SocketChannel socketChannel;
		
		public Process(SocketChannel socketChannel) {
			this.socketChannel = socketChannel;
		}

		@Override
		public void run() {
			try {
				ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
				socketChannel.read(byteBuffer);
				String reqMsg = new String(byteBuffer.array(), StandardCharsets.UTF_8);
				System.out.println("get req：" + reqMsg);
				String rspMsg = "resp：" + reqMsg;
				socketChannel.write(ByteBuffer.wrap(rspMsg.getBytes(StandardCharsets.UTF_8)));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
